<?php
namespace app\controller;

use app\BaseController;
use Kkokk\Poster\PosterManager;
use think\facade\Db;

class Index extends BaseController
{
    public function initialize()
    {
        header("access-control-allow-headers: Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,Login-Agent,X-Mx-ReqToken,X-Requested-With");
        header("access-control-allow-methods: GET, POST, PUT, DELETE, HEAD, OPTIONS,PATCH");
        header("access-control-allow-credentials: true");
        header("access-control-allow-origin: *");
    }

    public function materialList()
    {
        $list = Db::name('poster_material')->order('id desc')->select();
        return json(['code' => 0, 'data' => $list, 'msg' => 'success']);
    }

    public function materialAdd()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $param['create_time'] = date('Y-m-d H:i:s');
            Db::name('poster_material')->insert($param);

            return json(['code' => 0, 'data' => [], 'msg' => '添加成功']);
        }
    }

    public function materialDel()
    {
        $id = input('param.id');

        Db::name('poster_material')->where('id', $id)->delete();
        return json(['code' => 0, 'data' => [], 'msg' => '删除成功']);
    }

    public function posterList()
    {
        $list = Db::name('poster')->order('id desc')->select();
        return json(['code' => 0, 'data' => $list, 'msg' => 'success']);
    }

    public function posterAdd()
    {
        if (request()->isPost()) {

            $param = input('post.');

            $preview = $this->makePreview($param, 'cover');
            $addParam = [
                'name' => $param['name'],
                'preview' => request()->domain() . '/' . ltrim($preview['url'], './'),
                'status' => 1,
                'design_content' => json_encode($param),
                'create_time' => date('Y-m-d H:i:s')
            ];

            Db::name('poster')->insert($addParam);
            return json(['code' => 0, 'data' => [], 'msg' => '保存成功']);
        }
    }

    public function getPoster()
    {
        $id = input('param.id');

        $info = Db::name('poster')->where('id', $id)->find();
        return json(['code' => 0, 'data' => $info, 'msg' => 'success']);
    }

    // 上传图片
    public function upload()
    {
        $file = request()->file('file');
        $fileExt = $file->getOriginalExtension();
        $imageSize = getimagesize($file);

        // 移动到框架应用根目录/public/uploads/ 目录下
        $saveName = \think\facade\Filesystem::disk('public')->putFile('', $file);

        $res = [];
        $res['width'] = $imageSize[0];
        $res['height'] = $imageSize[1];
        $res['type'] = $fileExt;
        $res['url'] = request()->domain() . '/storage/' .  $saveName;

        return json(['code' => 0, 'data' => $res, 'msg' => '上传成功']);
    }

    public function preview()
    {
        try {

            $posterData = input('post.');
            $result = $this->makePreview($posterData);

            return json(['code' => 0, 'data' => request()->domain() . '/' . ltrim($result['url'], './'), 'msg' => 'success']);
        } catch (\Exception $e) {
            file_put_contents('./error.log', $e->getFile() . ' --- ' . $e->getLine() . ' --- ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            return json(['code' => -1, 'data' => [], 'msg' => $e->getMessage()]);
        }
    }

    protected function makePreview($posterData, $type = 'temp')
    {
        $name = uniqid();

        if ($type == 'temp') {
            $PosterManager = new PosterManager('./poster_preview/temp/' . $name . '.' . $posterData['type']);
        } else {
            $PosterManager = new PosterManager('./poster_preview/cover/' . $name . '.' . $posterData['type']);
        }

        $temp = $PosterManager;

        if ($posterData['activeName'] == 'img' && !empty($posterData['img_src'])) {
            $temp = $temp->buildImDst($posterData['img_src'], $posterData['width'], $posterData['height']);
        } else {
            $temp = $temp->buildIm($posterData['width'], $posterData['height'], $this->hex2rgba($posterData['color']));
        }

        if (isset($posterData['item']) && !empty($posterData['item'])) {
            foreach ($posterData['item'] as $vo) {
                if ($vo['t'] == 'text') {
                    $font = '/static/alifont/' . $vo['fn'] . '.woff';
                    $temp = $temp->buildText($vo['v'], $vo['x'], $vo['y'], $vo['s'], $this->hex2rgba($vo['c']), $vo['w'], $font);
                } else if ($vo['t'] == 'image') {
                    $temp = $temp->buildImage($vo['v'], $vo['x'], $vo['y'], 0, 0, $vo['w'], $vo['h'], $this->hex2rgba($vo['c']));
                } else if ($vo['t'] == 'qrcode') {
                    $temp = $temp->buildQr($vo['v'], $vo['x'], $vo['y'], 0, 0, $vo['w'], $vo['h'], 4, 1);
                }
            }
        }

        return $temp->getPoster();
    }

    protected function hex2rgba($color)
    {
        $hexColor = str_replace('#', '', $color);
        $lens = strlen($hexColor);

        if ($lens != 3 && $lens != 6) {
            return false;
        }

        $newColor = '';
        if ($lens == 3) {

            for ($i = 0; $i < $lens; $i++) {
                $newColor .= $hexColor[$i] . $hexColor[$i];
            }
        } else {

            $newColor = $hexColor;
        }

        $hex = str_split($newColor, 2);
        $rgba = [];

        foreach ($hex as $vls) {
            $rgba[] = hexdec($vls);
        }

        $rgba[] = 1;
        return $rgba;
    }
}
